package com.jsy.common.util.publicApi;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class SignatureUtil {
    private static final String HMAC_ALGORITHM = "HmacSHA256";
    
    // 生成请求签名
    public static String generateSignature(Map<String, String> params, String secretKey) {
        // 1. 排除签名参数
        params.remove("signature");
        
        // 2. 按参数名排序
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        
        // 3. 拼接参数名和值（key1=value1&key2=value2...）
        StringBuilder paramString = new StringBuilder();
        for (String key : keys) {
            paramString.append(key)
                       .append("=")
                       .append(params.get(key))
                       .append("&");
        }
        
        // 4. 移除最后一个&符号
        if (paramString.length() > 0) {
            paramString.deleteCharAt(paramString.length() - 1);
        }
        
        // 5. 使用HMAC-SHA256算法生成签名
        try {
            Mac mac = Mac.getInstance(HMAC_ALGORITHM);
            SecretKeySpec secretKeySpec = new SecretKeySpec(
                secretKey.getBytes(StandardCharsets.UTF_8), 
                HMAC_ALGORITHM
            );
            mac.init(secretKeySpec);
            byte[] hash = mac.doFinal(paramString.toString().getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(hash);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("Error generating signature", e);
        }
    }
    
    // 验证请求签名
    public static boolean verifySignature(Map<String, String> params, String secretKey, String providedSignature) {
        String generatedSignature = generateSignature(new HashMap<>(params), secretKey);
        return generatedSignature.equals(providedSignature);
    }
}